import React, { useState, useEffect } from 'react';
import {
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    TextField,
    Button,
    Box,
    FormControl,
    InputLabel,
    Select,
    MenuItem,
    Typography,
    Divider,
    IconButton,
    useTheme,
    useMediaQuery,
    Autocomplete,
    CircularProgress
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import EditIcon from '@mui/icons-material/Edit';
import { fuzzySearchOfferArea, fuzzySearchOfferSchool, fuzzySearchOfferProgram } from '../../../api';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import dayjs from 'dayjs';

// 通用字段类型
export interface Field {
    name: string;
    label: string;
    type:
        | 'text'
        | 'select'
        | 'date'
        | 'textarea'
        | 'hidden'
        | 'autocomplete'
        | 'school-autocomplete'
        | 'program-autocomplete'
        | 'year-picker'
        | 'month-picker';
    options?: Array<{ value: string; label: string }>;
    required?: boolean;
    disabled?: boolean;
    apiEndpoint?: string; // 用于autocomplete类型的API端点
}

// 通用对话框属性
interface EditDialogProps {
    open: boolean;
    onClose: () => void;
    title: string;
    data: Record<string, any> | null;
    fields: Field[];
    onSave: (updatedData: Record<string, any>) => void;
    onOfferTypeChange?: (offerType: string, formData: Record<string, any>) => void;
}

const EditDialog: React.FC<EditDialogProps> = ({ open, onClose, title, data, fields, onSave, onOfferTypeChange }) => {
    const [formData, setFormData] = useState<Record<string, any> | null>(null);
    const theme = useTheme();
    const fullScreen = useMediaQuery(theme.breakpoints.down('md'));

    // 自动完成相关状态 - 地区
    const [areaOptions, setAreaOptions] = useState<string[]>([]);
    const [areaLoading, setAreaLoading] = useState<boolean>(false);
    const [areaInputValue, setAreaInputValue] = useState<string>('');

    // 自动完成相关状态 - 学校
    const [schoolOptions, setSchoolOptions] = useState<string[]>([]);
    const [schoolLoading, setSchoolLoading] = useState<boolean>(false);
    const [schoolInputValue, setSchoolInputValue] = useState<string>('');

    // 自动完成相关状态 - 职位/项目
    const [programOptions, setProgramOptions] = useState<string[]>([]);
    const [programLoading, setProgramLoading] = useState<boolean>(false);
    const [programInputValue, setProgramInputValue] = useState<string>('');

    useEffect(() => {
        if (data) {
            setFormData({ ...data });
        } else {
            // 如果没有传入数据，创建一个空的表单数据对象
            const emptyData: Record<string, any> = {};
            fields.forEach((field) => {
                emptyData[field.name] = '';
            });
            setFormData(emptyData);
        }
    }, [data, fields, open]);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        const { name, value } = e.target;
        if (formData) {
            setFormData({
                ...formData,
                [name]: value
            });
        }
    };

    const handleSelectChange = (e: any) => {
        const { name, value } = e.target;
        if (formData) {
            // 如果是offer类型变化，并且是在Offer信息编辑对话框中
            if (name === 'offerType' && title.includes('Offer信息')) {
                let updatedFormData;

                // 如果选择"就业"，清除项目类型字段
                if (value === '就业') {
                    updatedFormData = {
                        ...formData,
                        [name]: value,
                        projectType: ''
                    };
                }
                // 如果选择"升学"，清除月薪和年薪字段
                else if (value === '升学') {
                    updatedFormData = {
                        ...formData,
                        [name]: value,
                        salaryMonth: '',
                        salaryYear: '',
                        industryName: ''
                    };
                }

                // 更新表单数据
                if (updatedFormData) {
                    setFormData(updatedFormData);

                    // 如果提供了onOfferTypeChange回调，调用它来更新字段列表
                    if (onOfferTypeChange) {
                        onOfferTypeChange(value, updatedFormData);
                    }
                }
            } else {
                // 对于其他字段，正常更新
                setFormData({
                    ...formData,
                    [name]: value
                });
            }
        }
    };

    let i = 0;
    const getOptionKey = (option: string) => {
        i++;
        return `${option}${i}`;
    };

    // 处理地区搜索
    const handleAreaSearch = async (value: string, fieldName: string) => {
        setAreaInputValue(value);

        if (value.trim().length < 1) {
            setAreaOptions([]);
            return;
        }

        setAreaLoading(true);
        try {
            const results = await fuzzySearchOfferArea(value);
            setAreaOptions(results);
        } catch (error) {
            console.error('搜索地点失败:', error);
            setAreaOptions([]);
        } finally {
            setAreaLoading(false);
        }
    };

    // 处理地区选择
    const handleAreaSelect = (fieldName: string, value: string | null) => {
        if (formData) {
            setFormData({
                ...formData,
                [fieldName]: value || ''
            });
        }

        // 清空搜索输入值，使下拉框关闭
        setAreaInputValue('');
    };

    // 处理学校名称搜索
    const handleSchoolSearch = async (value: string, fieldName: string) => {
        setSchoolInputValue(value);

        if (value.trim().length < 1) {
            setSchoolOptions([]);
            return;
        }

        setSchoolLoading(true);
        try {
            const results = await fuzzySearchOfferSchool(value);
            setSchoolOptions(results);
        } catch (error) {
            console.error('搜索企业/学校名称失败:', error);
            setSchoolOptions([]);
        } finally {
            setSchoolLoading(false);
        }
    };

    // 处理学校名称选择
    const handleSchoolSelect = (fieldName: string, value: string | null) => {
        if (formData) {
            setFormData({
                ...formData,
                [fieldName]: value || ''
            });
        }

        // 清空搜索输入值，使下拉框关闭
        setSchoolInputValue('');
    };

    // 处理职位/项目搜索
    const handleProgramSearch = async (value: string, fieldName: string) => {
        setProgramInputValue(value);

        if (value.trim().length < 1) {
            setProgramOptions([]);
            return;
        }

        setProgramLoading(true);
        try {
            const results = await fuzzySearchOfferProgram(value);
            setProgramOptions(results);
        } catch (error) {
            console.error('搜索职位/项目名称失败:', error);
            setProgramOptions([]);
        } finally {
            setProgramLoading(false);
        }
    };

    // 处理职位/项目选择
    const handleProgramSelect = (fieldName: string, value: string | null) => {
        if (formData) {
            setFormData({
                ...formData,
                [fieldName]: value || ''
            });
        }

        // 清空搜索输入值，使下拉框关闭
        setProgramInputValue('');
    };

    // 处理年份选择
    const handleYearChange = (fieldName: string, date: dayjs.Dayjs | null) => {
        if (formData) {
            if (date) {
                setFormData({
                    ...formData,
                    [fieldName]: date.format('YYYY')
                });
            } else {
                // 如果用户清除了日期，设置为空字符串
                setFormData({
                    ...formData,
                    [fieldName]: ''
                });
            }
        }
    };

    // 处理年月选择
    const handleMonthChange = (fieldName: string, date: dayjs.Dayjs | null) => {
        if (formData) {
            if (date) {
                setFormData({
                    ...formData,
                    [fieldName]: date.format('YYYY-MM')
                });
            } else {
                // 如果用户清除了日期，设置为空字符串
                setFormData({
                    ...formData,
                    [fieldName]: ''
                });
            }
        }
    };

    const handleSubmit = () => {
        if (formData) {
            onSave(formData);
        }
        onClose();
    };

    if (!formData) return null;

    return (
        <Dialog
            open={open}
            onClose={onClose}
            maxWidth="md"
            fullWidth
            fullScreen={fullScreen}
            slotProps={{
                paper: {
                    sx: {
                        borderRadius: 2,
                        boxShadow: '0 12px 28px rgba(0,0,0,0.15)',
                        overflow: 'hidden'
                    }
                }
            }}>
            <DialogTitle
                sx={{
                    p: 2,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    bgcolor: 'primary.main',
                    color: 'white'
                }}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    <EditIcon sx={{ mr: 1 }} />
                    <Typography variant="h6" component="div" sx={{ fontWeight: 500 }}>
                        {title}
                    </Typography>
                </Box>
                <IconButton
                    aria-label="close"
                    onClick={onClose}
                    sx={{
                        color: 'white',
                        '&:hover': {
                            backgroundColor: 'rgba(255,255,255,0.1)'
                        }
                    }}>
                    <CloseIcon />
                </IconButton>
            </DialogTitle>

            <DialogContent sx={{ p: 3 }}>
                <Box
                    sx={{
                        display: 'grid',
                        gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))',
                        gap: 2,
                        pt: 2
                    }}>
                    {fields.map((field) =>
                        field.type === 'hidden' ? (
                            <input
                                key={field.name}
                                type="hidden"
                                name={field.name}
                                value={formData[field.name] || ''}
                            />
                        ) : field.type === 'textarea' ? (
                            <Box key={field.name} sx={{ gridColumn: '1 / -1' }}>
                                <InputLabel htmlFor={field.name}>{field.label}</InputLabel>
                                <TextField
                                    id={field.name}
                                    name={field.name}
                                    fullWidth
                                    value={formData[field.name] || ''}
                                    onChange={handleChange}
                                    variant="outlined"
                                    size="small"
                                    required={field.required}
                                    disabled={field.disabled}
                                    multiline
                                    rows={4}
                                    sx={{ borderRadius: 1 }}
                                />
                            </Box>
                        ) : field.type === 'date' ? (
                            <Box key={field.name}>
                                <InputLabel htmlFor={field.name}>{field.label}</InputLabel>
                                <TextField
                                    id={field.name}
                                    name={field.name}
                                    type="date"
                                    fullWidth
                                    value={formData[field.name] || ''}
                                    onChange={handleChange}
                                    variant="outlined"
                                    size="small"
                                    required={field.required}
                                    disabled={field.disabled}
                                    InputLabelProps={{
                                        shrink: true
                                    }}
                                    sx={{ borderRadius: 1 }}
                                />
                            </Box>
                        ) : field.type === 'year-picker' ? (
                            <Box key={field.name}>
                                <InputLabel htmlFor={field.name}>{field.label}</InputLabel>
                                <LocalizationProvider dateAdapter={AdapterDayjs}>
                                    <DatePicker
                                        views={['year']}
                                        value={formData[field.name] ? dayjs(formData[field.name]) : null}
                                        onChange={(date) => handleYearChange(field.name, date)}
                                        slotProps={{
                                            textField: {
                                                id: field.name,
                                                name: field.name,
                                                fullWidth: true,
                                                variant: 'outlined',
                                                size: 'small',
                                                required: field.required,
                                                disabled: field.disabled,
                                                sx: { borderRadius: 1 }
                                            }
                                        }}
                                    />
                                </LocalizationProvider>
                            </Box>
                        ) : field.type === 'month-picker' ? (
                                <Box key={field.name}>
                                    <InputLabel htmlFor={field.name}>{field.label}</InputLabel>
                                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                                        <DatePicker
                                            views={['year', 'month']}
                                            value={formData[field.name] ? dayjs(formData[field.name]) : null}
                                            onChange={(date) => handleMonthChange(field.name, date)}
                                            slotProps={{
                                                textField: {
                                                    id: field.name,
                                                    name: field.name,
                                                    fullWidth: true,
                                                    variant: 'outlined',
                                                    size: 'small',
                                                    required: field.required,
                                                    disabled: field.disabled,
                                                    sx: { borderRadius: 1 }
                                                }
                                            }}
                                        />
                                    </LocalizationProvider>
                                </Box>
                            ) : field.type === 'select' ? (
                            <Box key={field.name}>
                                <InputLabel htmlFor={field.name}>{field.label}</InputLabel>
                                <FormControl fullWidth size="small">
                                    <Select
                                        id={field.name}
                                        name={field.name}
                                        value={formData[field.name] || ''}
                                        onChange={handleSelectChange}
                                        required={field.required}
                                        disabled={field.disabled}
                                        sx={{ borderRadius: 1 }}>
                                        {field.options?.map((option) => (
                                            <MenuItem key={option.value} value={option.value}>
                                                {option.label}
                                            </MenuItem>
                                        ))}
                                    </Select>
                                </FormControl>
                            </Box>
                        ) : field.type === 'autocomplete' ? (
                            <Box key={field.name}>
                                <InputLabel htmlFor={field.name}>{field.label}</InputLabel>
                                <Autocomplete
                                    id={field.name}
                                    freeSolo
                                    options={areaOptions}
                                    value={formData[field.name] || ''}
                                    inputValue={areaInputValue}
                                    getOptionKey={getOptionKey}
                                    onInputChange={(_, newInputValue) => {
                                        handleAreaSearch(newInputValue, field.name);
                                    }}
                                    onChange={(_, newValue) => {
                                        handleAreaSelect(field.name, newValue);
                                    }}
                                    loading={areaLoading}
                                    loadingText="搜索中..."
                                    noOptionsText="无匹配结果"
                                    renderInput={(params) => (
                                        <TextField
                                            {...params}
                                            name={field.name}
                                            variant="outlined"
                                            size="small"
                                            required={field.required}
                                            disabled={field.disabled}
                                            InputProps={{
                                                ...params.InputProps,
                                                endAdornment: (
                                                    <React.Fragment>
                                                        {areaLoading ? (
                                                            <CircularProgress color="inherit" size={20} />
                                                        ) : null}
                                                        {params.InputProps.endAdornment}
                                                    </React.Fragment>
                                                )
                                            }}
                                        />
                                    )}
                                    sx={{ borderRadius: 1 }}
                                />
                            </Box>
                        ) : field.type === 'school-autocomplete' ? (
                            <Box key={field.name}>
                                <InputLabel htmlFor={field.name}>{field.label}</InputLabel>
                                <Autocomplete
                                    id={field.name}
                                    freeSolo
                                    options={schoolOptions}
                                    value={formData[field.name] || ''}
                                    inputValue={schoolInputValue}
                                    getOptionKey={getOptionKey}
                                    onInputChange={(_, newInputValue) => {
                                        handleSchoolSearch(newInputValue, field.name);
                                    }}
                                    onChange={(_, newValue) => {
                                        handleSchoolSelect(field.name, newValue);
                                    }}
                                    loading={schoolLoading}
                                    loadingText="搜索中..."
                                    noOptionsText="无匹配结果"
                                    renderInput={(params) => (
                                        <TextField
                                            {...params}
                                            name={field.name}
                                            variant="outlined"
                                            size="small"
                                            required={field.required}
                                            disabled={field.disabled}
                                            InputProps={{
                                                ...params.InputProps,
                                                endAdornment: (
                                                    <React.Fragment>
                                                        {schoolLoading ? (
                                                            <CircularProgress color="inherit" size={20} />
                                                        ) : null}
                                                        {params.InputProps.endAdornment}
                                                    </React.Fragment>
                                                )
                                            }}
                                        />
                                    )}
                                    sx={{ borderRadius: 1 }}
                                />
                            </Box>
                        ) : field.type === 'program-autocomplete' ? (
                            <Box key={field.name}>
                                <InputLabel htmlFor={field.name}>{field.label}</InputLabel>
                                <Autocomplete
                                    id={field.name}
                                    freeSolo
                                    options={programOptions}
                                    value={formData[field.name] || ''}
                                    inputValue={programInputValue}
                                    getOptionKey={getOptionKey}
                                    onInputChange={(_, newInputValue) => {
                                        handleProgramSearch(newInputValue, field.name);
                                    }}
                                    onChange={(_, newValue) => {
                                        handleProgramSelect(field.name, newValue);
                                    }}
                                    loading={programLoading}
                                    loadingText="搜索中..."
                                    noOptionsText="无匹配结果"
                                    renderInput={(params) => (
                                        <TextField
                                            {...params}
                                            name={field.name}
                                            variant="outlined"
                                            size="small"
                                            required={field.required}
                                            disabled={field.disabled}
                                            InputProps={{
                                                ...params.InputProps,
                                                endAdornment: (
                                                    <React.Fragment>
                                                        {programLoading ? (
                                                            <CircularProgress color="inherit" size={20} />
                                                        ) : null}
                                                        {params.InputProps.endAdornment}
                                                    </React.Fragment>
                                                )
                                            }}
                                        />
                                    )}
                                    sx={{ borderRadius: 1 }}
                                />
                            </Box>
                        ) : (
                            <Box key={field.name}>
                                <InputLabel htmlFor={field.name}>{field.label}</InputLabel>
                                <TextField
                                    id={field.name}
                                    name={field.name}
                                    fullWidth
                                    value={formData[field.name] || ''}
                                    onChange={handleChange}
                                    variant="outlined"
                                    size="small"
                                    required={field.required}
                                    disabled={field.disabled}
                                    sx={{ borderRadius: 1 }}
                                />
                            </Box>
                        )
                    )}
                </Box>
            </DialogContent>

            <Divider />

            <DialogActions sx={{ px: 3, py: 2, justifyContent: 'flex-end' }}>
                <Button
                    onClick={onClose}
                    variant="outlined"
                    sx={{
                        borderRadius: 1.5,
                        px: 3,
                        py: 0.75
                    }}>
                    取消
                </Button>
                <Button
                    onClick={handleSubmit}
                    variant="contained"
                    color="primary"
                    sx={{
                        borderRadius: 1.5,
                        px: 3,
                        py: 0.75,
                        boxShadow: '0 4px 10px rgba(0, 0, 0, 0.1)',
                        '&:hover': {
                            boxShadow: '0 6px 12px rgba(0, 0, 0, 0.15)'
                        }
                    }}>
                    保存
                </Button>
            </DialogActions>
        </Dialog>
    );
};

export default EditDialog;
